<template>
  <div style="position: relative">
    <div
      id="tencMap"
      class="tencMap"
      style="position: relative; z-index: 1"
      :style="{ height: height, width: width }"
    />
    <el-select
      class="form-input-large-super"
      style="position: absolute; top: 10px; left: 50px; z-index: 2"
      v-model="selectLocation"
      filterable
      remote
      placeholder="请输入位置关键字"
      :remote-method="searchLocation"
      :loading="loading"
    >
      <i slot="prefix" class="el-icon-search" style="font-size: 19px; margin-top: 10px"></i>

      <el-option
        v-for="item in locationData"
        :key="item.id"
        :label="item.title"
        :value="item.location.lat + ',' + item.location.lng + ',' + item.title"
      >
      </el-option>
    </el-select>
  </div>
</template>

<script>
export default {
  name: 'TMap',
  props: {
    value: Object,
    width: {
      type: String,
      default: '800px'
    },
    height: {
      type: String,
      default: '400px'
    }
  },
  data() {
    return {
      selectLocation: '',
      mapInstance: null,
      loading: false,
      locationData: [],
      clickselect: false,
      infoWindow: null
    }
  },
  computed: {
    formData: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  watch: {
    selectLocation() {
      if (!this.selectLocation) {
        return
      }
      let locationInfo = this.selectLocation.split(',')
      this.formData.latitude = locationInfo[0]
      this.formData.longitude = locationInfo[1]
      this.formData.address = locationInfo[2]
      const { longitude, latitude } = this.formData
      if (this.mapInstance) {
        this.mapInstance.setCenter(new TMap.LatLng(latitude, longitude))
      }
      if (this.infoWindow) {
        this.infoWindow.close()
        this.infoWindow.destroy()
        this.infoWindow = null
      }
      this.infoWindow = new TMap.InfoWindow({
        map: this.mapInstance,
        position: new TMap.LatLng(latitude, longitude), // 设置信息框位置
        content: this.formData.address // 设置信息框内容
      })
      this.infoWindow.open()
    }
  },
  mounted() {
    this.initTencMap()
    this.initLocation()
  },
  destroyed() {
    if (this.mapInstance) {
      this.mapInstance.destroy()
      this.mapInstance = null
    }
  },
  methods: {
    // 初始化腾讯地图
    initTencMap() {
      const { longitude, latitude } = this.value
      let center = new TMap.LatLng(latitude || 28.111903, longitude || 113.029371)
      let map = new TMap.Map('tencMap', {
        rotation: 45, // 设置地图旋转角度
        pitch: 30, // 设置俯仰角度（0~45）
        zoom: 17, // 设置地图缩放级别
        center: center // 设置地图中心点坐标
      })
      this.mapInstance = map
      map.on('click', evt => {
        let longitude = evt.latLng.getLng().toFixed(6)
        let latitude = evt.latLng.getLat().toFixed(6)
        this.locationGeocoder(latitude, longitude)
        this.formData.longitude = longitude
        this.formData.latitude = latitude
      })
    },
    // 逆地理解析
    locationGeocoder(lat, lng) {
      const url = 'https://apis.map.qq.com/ws/geocoder/v1/?location='
      this.$jsonp(url, {
        location: lat + ',' + lng,
        get_poi: '0',
        key: 'IILBZ-UO5RJ-EWHFP-KMILG-SHY5Q-63BWX',
        output: 'jsonp',
        callbackName: 'res'
      }).then(res => {
        if (res.status === 0) {
          const { result } = res
          this.formData.address = result.address
          if (this.infoWindow) {
            this.infoWindow.close()
            this.infoWindow.destroy()
            this.infoWindow = null
          }
          this.infoWindow = new TMap.InfoWindow({
            map: this.mapInstance,
            position: new TMap.LatLng(lat, lng), // 设置信息框位置
            content: this.formData.address // 设置信息框内容
          })
          this.infoWindow.open()
        }
      })
    },
    // 根据关键字搜索地址
    searchLocation(query) {
      if (!query) {
        return
      }
      this.loading = true
      const city = '长沙'
      const url = 'https://apis.map.qq.com/ws/place/v1/suggestion'
      this.$jsonp(url, {
        keyword: query,
        region_fix: 0,
        region: 'region(' + city + ')',
        key: 'IILBZ-UO5RJ-EWHFP-KMILG-SHY5Q-63BWX',
        output: 'jsonp',
        callbackName: 'res'
      }).then(res => {
        if (res.status === 0) {
          this.loading = false
          const { data } = res
          this.locationData = data
          if (this.clickselect) {
            this.selectLocation =
              data[0].location.lat + ',' + data[0].location.lng + ',' + data[0].title
            this.clickselect = false
          }
        }
      })
    },
    // 初始化定位
    initLocation() {
      var geolocation = new qq.maps.Geolocation()
      var options = {
        timeout: 10000
      }
      geolocation.getIpLocation(this.showPosition, this.showErr, options)
    },
    showPosition(position) {
      const { lng, lat } = position
      this.formData.longitude = lng
      this.formData.latitude = lat
      this.locationGeocoder(lat, lng)
      if (this.mapInstance) {
        this.mapInstance.setCenter(new TMap.LatLng(lat, lng))
      }
    },
    showErr(error) {
      console.log(error, '定位失败')
    }
  }
}
</script>

<style lang="scss" scoped></style>
